package com.etone.smartAudit.utils;

import com.alibaba.fastjson.JSONObject;

import java.util.Map;

/**
 * @author: sovy
 * @date: 2020/11/25
 * @description:
 */
public class ObjectUtil {

    /**
     * bean转map
     *
     * @param obj
     * @return
     */
    public static Map<String, Object> toMap(Object obj) {
        String jsonString = JSONObject.toJSONString(obj);
        Map<String, Object> map = JSONObject.parseObject(jsonString, Map.class);
        return map;
    }

    /**
     * 判断是否是基本类型
     *
     * @param object
     * @return
     */
    public static boolean isBaseType(Object object) {
        Class className = object.getClass();
        return className.equals(Integer.class) ||
                className.equals(String.class) ||
                className.equals(Byte.class) ||
                className.equals(Long.class) ||
                className.equals(Double.class) ||
                className.equals(Float.class) ||
                className.equals(Character.class) ||
                className.equals(Short.class) ||
                className.equals(Boolean.class);
    }

    public static Double obj2Double(Object obj) {
        if (obj == null) {
            return null;
        }
        return Double.valueOf(String.valueOf(obj));
    }

    /**
     * 求两个Object的百分比,保留两位小数
     *
     * @param obj1
     * @param obj2
     * @return
     */
    public static Double calcPercent(Object obj1, Object obj2) {
        if (obj1 == null || obj2 == null) {
            return null;
        }

        Double s2 = obj2Double(obj2);
        if (s2 == 0D) {
            return 0D;
        }
        Double s1 = obj2Double(obj1);
        return NumberUtil.double2decimal(s1 * 100D / s2);
    }

    public static Integer objToInteger(Object obj) {
        if (obj == null) {
            return null;
        }
        return Integer.valueOf(String.valueOf(obj));
    }
}
